package com.michaelwolf.mytool.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.GZIPInputStream;

public class GZIPTool {

	public static void main(String[] args) throws Exception {
		String zipFile = "E:/2017-12-08_110957.txt.gz";
		System.out.println(doUncompressFile(zipFile));
	}

	/**
	 * Uncompress the incoming file.
	 * 
	 * @param inFileName
	 *            Name of the file to be uncompressed
	 */
	public static String doUncompressFile(String inFileName) throws Exception {
		if (!getExtension(inFileName).equalsIgnoreCase("gz")) {
			throw new Exception("File name must have extension of \".gz\"");
		}
		String outFileName = getFileName(inFileName);
		if(new File(outFileName).exists()){
			System.out.println("file "+ outFileName + " exists, no unzip operation run");
			return outFileName;
		}

		GZIPInputStream in = new GZIPInputStream(
				new FileInputStream(inFileName));

		
		FileOutputStream out = new FileOutputStream(outFileName);

		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}

		in.close();
		out.close();

		return outFileName;
	}

	/**
	 * Used to extract and return the extension of a given file.
	 * 
	 * @param f
	 *            Incoming file to get the extension of
	 * @return <code>String</code> representing the extension of the incoming
	 *         file.
	 */
	private static String getExtension(String f) {
		String ext = "";
		int i = f.lastIndexOf('.');

		if (i > 0 && i < f.length() - 1) {
			ext = f.substring(i + 1);
		}
		return ext;
	}

	/**
	 * Used to extract the filename without its extension.
	 * 
	 * @param f
	 *            Incoming file to get the filename
	 * @return <code>String</code> representing the filename without its
	 *         extension.
	 */
	private static String getFileName(String f) {
		String fname = "";
		int i = f.lastIndexOf('.');

		if (i > 0 && i < f.length() - 1) {
			fname = f.substring(0, i);
		}
		return fname;
	}
}
